package com.ying.pubsub;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.ying.util.RabbitMQUtils;

import java.io.IOException;

/**
 * ClassName: PubSubProducer
 * Package: com.ying.pubsub
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/3/23 21:36
 * @Version 1.0
 */
public class PubSubProducer {
    private static final String EXCHANGE_NAME = "fanoutExchange";
    private static final String QUEUE_NAME = "fanoutQueue";

    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtils.getConnection("192.168.160.134", 5672, "myHV",
                "testUser", "123456");

        Channel channel = connection.createChannel();

        //2.创建exchange
        /**
         *
         exchange – 交换机名称
         type – 交换机类型
             DIRECT(定向交换机):把消息交给符合指定routing key的队列
             FANOUT(扇形交换机):广播消息。扇形交换机会把能接收到的消息全部发送给
             绑定在自己身上的队列
             TOPIC(主题交换机):会将消息交给匹配规则的队列上
             HEADERS:会将消息交给匹配头部参数的队列上
         durable – 是否持久化,设置成true,重启RabbitMQ依然存在
         autoDelete – 自动删除,设置成 true如果交换机不再使用,将自动删除
         internal – 表示是否是内置的交换机
         arguments – 交换机的其它参数
         */
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT,true,false,false,null);

        //3.创建两个队列
        for (int i = 1; i <= 2; i++) {
            channel.queueDeclare(QUEUE_NAME + i, true, false, false, null);

            //4.将交换机和队列绑定
            /**
             *
             queue – 绑定的队列名称
             exchange – 绑定的交换机名称
             routingKey – 路由key(规则),扇形交换机设置为""
             arguments – 绑定参数
             */
            channel.queueBind(QUEUE_NAME + i, EXCHANGE_NAME, "", null);
        }
        //4.发送消息(交换机->队列)
        channel.basicPublish(EXCHANGE_NAME, "",null, "模拟删除balabala".getBytes());
        //5.释放资源
        RabbitMQUtils.release(connection, channel);
    }
}
